<template>
  <div class="pages" v-cloak>
    <div class="pageLevel split-grade">
      <!--   操作框     -->
      <div class="tableSearch">
        <el-form>
          <el-form-item label="" label-width="15px">
            <el-button type="primary" icon="el-icon-plus" size='mini' @click="paymentDialogVisible = true" key='add' v-if='setRole("新建")'>新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table ref="multipleTable" :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="80" align='center'></el-table-column>
          <el-table-column prop="gradeName" align="center" label="等级名称"></el-table-column>
          <el-table-column prop="serviceProviderGradeName" align="center" label="毛利">
            <template slot-scope='scope'>
              <div v-if="scope.row.beginProfit==0">
                {{scope.row.endProfit}}%以下
              </div>
              <div v-else-if="scope.row.beginProfit!=0&&scope.row.endProfit!=0">
                  <span>{{scope.row.beginProfit}}%-{{scope.row.endProfit}}%</span>
              </div>
              <div v-else-if="scope.row.endProfit==0">
                  {{scope.row.beginProfit}}%以上
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="isBenefit" align="center" label="是否参与分润">
            <template slot-scope='scope'>
              <span>{{scope.row.isBenefit ? '否' : '是'}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click='editItem(scope.$index)'  v-if='setRole("修改")'>修改</el-button>
              <el-button type="text" size='small' @click="deleTableData(scope.row.id)"  v-if='setRole("删除")'>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pageblock">
        <el-pagination @current-change="handleCurrentChange" :current-page="pageNum"   layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
      <!--      弹框-->
      <el-dialog title="新建商品分润等级" :visible.sync="paymentDialogVisible" width="500px" center :show-close=false :close-on-click-modal=false :close-on-press-escape=false>
          <el-form label-width="150px" label-position='left' :model="creatItem" :rules="rulesCreatItem" ref="creatItem">
            <el-form-item label="等级名称：" prop='gradeName'>
              <el-input size='small' v-model='creatItem.gradeName' clearable maxlength='30'></el-input>
            </el-form-item>
            <el-form-item label="毛利区间（包含）：" class='split-range' prop='beginProfit'>
              <el-input size='small' v-model='creatItem.beginProfit' maxlength='30' style='width: 115px;'
                        @keyup.native='replace(creatItem,"beginProfit")'></el-input>
              <span>%——</span>
              <el-input size='small' v-model='creatItem.endProfit' maxlength='30' style='width: 115px'
                        @keyup.native='replace(creatItem,"endProfit")'></el-input>
              <span>%</span>
            </el-form-item>
            <el-form-item label="是否参与分润：">
              <el-switch v-model="creatItem.isBenefit" active-text="是" inactive-text="否" @change='switchChange($event)'
                         :active-value="0" :inactive-value="1">
              </el-switch>
            </el-form-item>
            <el-form-item label="" label-width='0px' style='text-align: center;margin-top: 50px'>
              <el-button type="primary" size='small' plain key='no' @click='cancel()'>取 消</el-button>
              <el-button type="primary" size='small' key='yes' @click='addSplitItem(creatItem.id, "creatItem")'>确 定</el-button>
            </el-form-item>
           </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import util from '@/util'
  import { mapState } from "vuex";
  import {
    findBenefitGradeList,
    addOrUpdateBenefitGrade,
    deleteBenefitGrade
  } from "@/api";
import { constants } from 'zlib';
    export default {
        name: "split-grade",
      data () {
        const validProfit = (rule, value, callback)=> {
          if(this.creatItem.endProfit === ''){
            return callback(new Error('请输入毛利区间'));
          }
          if(this.creatItem.beginProfit == 0 && this.creatItem.endProfit == 0){
            return callback(new Error('毛利不能为0'));
          }
          if((this.creatItem.beginProfit && !util.validFloatNumber(this.creatItem.beginProfit)) ||
            (this.creatItem.endProfit && !util.validFloatNumber(this.creatItem.endProfit))) {
            return callback(new Error('只能输入数字或者小数点'));
          }
          if(String(value).indexOf('.')>0){
            let arr = value.split('.')
            if(arr[0].length>2 && parseInt(arr[1]) > 0){
              return callback(new Error('数值不能大于100'));
            }  else if(this.creatItem.endProfit && this.creatItem.beginProfit && this.creatItem.endProfit < this.creatItem.beginProfit){
              return callback(new Error('右侧值应大于等于左侧'));
            }else {
              callback();
            }
          }else if(this.creatItem.endProfit && this.creatItem.beginProfit && parseInt(this.creatItem.endProfit) < parseInt(this.creatItem.beginProfit)&&parseInt(this.creatItem.endProfit)!=0){
            return callback(new Error('右侧值应大于等于左侧'));
          }else if(String(value).indexOf('.')<=0){
            if(parseInt(value) > 100){
              return callback(new Error('数值不能大于100'));
            }else{
               callback();
            }
          }else{
            callback()
          }
          callback();
        };
          return {
            paymentDialogVisible:false,
            creatItem: {
              benefitGradeId: '', //商品分润等级Id
              gradeName: '',
              beginProfit: '', //毛利起始百分比
              endProfit: '', //毛利终止百分比
              isBenefit: 0, //是否参与分润：0-参与，1-不参与
              shopId: '' //商户id
            },
            tableData: [],
            rulesCreatItem: {
              gradeName: [{required: true, message: '请输入等级名称', trigger: 'blur'}],
              beginProfit: [{required: true, message: '请输入毛利区间', trigger: 'blur'},
                {validator: validProfit, trigger: 'blur'}],
            },
            pageSize: 10,
            pageNum: 1,
            total: 0
          }
      },
      computed: mapState([
        "merchantId",
        "sub",
        'power',
        "isReLoadData"]),
      created() {
          this.getTableDate('1')
      },
      methods: {
        setRole (key) {
          return util.selectTitle(this.power, key)
        },
          //字符串过滤
        replace(obj,key) {
          let that = this
          let event = event || window.event
          if(event.keyCode == 13){
            setTimeout(()=>{
              that.validItem(obj,key);
            },100);
          } else {
            that.validItem(obj,key);
          }
        },
        validItem(obj,key){
          let res = util.replaceNum(obj[key],3);
          this.$set(obj,key,res);
        },
        handleCurrentChange(val) {
          this.getTableData(val);
        },
        //获取列表数据
          getTableDate(pageNum) {
            let data = {
              shopId: this.merchantId,
              pageNum: pageNum,
              pageSize: this.pageSize
            }
            findBenefitGradeList(data).then(res=>{
              if(res.code == 200) {
                this.tableData = res.data.list;
                this.total = res.data.pageTotal
              }
            })
          },
        //编辑
        editItem(index) {
          this.creatItem = JSON.parse(JSON.stringify(this.tableData[index]))
          this.paymentDialogVisible = true
        },
        //新增
        addSplitItem(id = '', formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let data = JSON.parse(JSON.stringify(this.creatItem));
              if (id == '' && data.shopId == '') {
                data.shopId = this.merchantId
              }
              data.benefitGradeId = id
              addOrUpdateBenefitGrade(data).then(res =>{
                if(res.code == 200){
                  this.getTableDate('1');
                  this.cancel();
                  this.tips(res.msg, 'success')
                }
              })
            }
          });
        },
        deleTableData(id) {
          this.$confirm('删除该商品等级后，所有服务商该等级的商品将不再享受分润，是否继续删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            showClose: false
          }).then(() => {
            //确定执行的操作
            deleteBenefitGrade({
              benefitGradeId: id
            }).then(res=>{
              if(res.code == 200) {
                this.tips('删除成功', 'success');
                this.getTableDate('1');
              } 
            })
          }).catch(() => {
            //取消执行的操作
          });
        },
        switchChange() {

        },
        cancel() {
          this.$refs.creatItem.clearValidate();
          this.paymentDialogVisible = false;
          for (let k of Object.keys(this.creatItem)) {
            if(k ==  'isBenefit'){
              this.creatItem[k] = 0
            }else {
              this.creatItem[k] = ''
            }
          }
        },
        tips(tip,type) {
          this.$message({
            message: tip,
            type: type
          });
        },
      }
    }
</script>

<style scoped lang='less'>
  .pages{
    position: absolute;
    top: 70px;
    left: 11px;
    right: 11px;
    bottom: 10px;
    // overflow: auto;
  }
  .split-grade{
    .el-dialog__header{
      background: #409EFF;
      color: #fff;
    }
  }
</style>
<style lang='less'>
  .split-grade{
  .el-dialog__header{
    background-color: #409EFF;
    .el-dialog__title{
      color: #fff;
    }
  }
    .split-range{
      display: inline-block;
      input{
        text-align: center;
        padding: 0 5px;
      }
    }
  }
</style>
